use regex::Regex;
use serde_json::{json, Map, Value};

/// 通过 data 参数，获取数据库查询条件
/// ```
/// <el-input size="mini" v-model="searchForm.like$plate_no" style="width: 200px;"
///  @keyup.enter.native="searchDataInfo" placeholder=""></el-input>
///
/// 会自动添加搜索语句 "plate_no like '%?%'"
///
/// <el-date-picker size="mini" v-model="searchForm.range$last_in_time" type="daterange"
/// value-format="timestamp" :default-time="['00:00:00', '23:59:59']" style="width: 200px;"
/// range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期">
/// </el-date-picker>
///
/// 会自动添加搜索语句 "last_in_time between ? and ?"
///
///
/// ```
pub fn get_db_where_datas(data: &Value) -> Map<String, Value> {
    let mut where_data = serde_json::Map::new();

    if let Some(obj) = data.as_object() {
        obj.iter().for_each(|item| {
            let key = item.0;
            let val = item.1;

            //log::debug!("参数:{:?}", item);
            if let Ok(re) = Regex::new("^([0-9A-Za-z_]+)\\$([0-9A-Za-z_]+)$") {
                if let Some(cap) = re.captures(key) {
                    if cap.len() > 2 {
                        let action = cap.get(1).unwrap().as_str();
                        let field = cap.get(2).unwrap().as_str();
                        //log::debug!("查询事件:{}  查询字段:{}", action, field);
                        match action {
                            "like" => {
                                if let Some(v) = val.as_str() {
                                    where_data.insert(format!("{} like ?", field), json!(format!("%{}%", v.trim())));
                                }
                            }
                            "like_str" => {
                                if let Some(v) = val.as_str() {
                                    where_data.insert(format!("{} like ?", field), json!(format!("%{}%", v.trim())));
                                }
                            }
                            "equals" => {
                                if val.is_number() {
                                    where_data.insert(format!("{} = ?", field), val.clone());
                                } else if val.is_string() {
                                    if let Some(v) = val.as_str() {
                                        where_data.insert(format!("{} = ?", field), json!(v.trim()));
                                    }
                                }
                            }
                            "equals_int" => {
                                if val.is_number() {
                                    where_data.insert(format!("{} = ?", field), val.clone());
                                }
                            }
                            "equals_str" => {
                                if val.is_string() {
                                    if let Some(v) = val.as_str() {
                                        where_data.insert(format!("{} = ?", field), json!(v.trim()));
                                    }
                                }
                            }
                            "range" => {
                                if let Some(arr) = val.as_array() {
                                    if arr.len() == 2 {
                                        where_data.insert(format!("{} between ? and ?", field), val.clone());
                                    }
                                }
                            }
                            "range_int" => {
                                if let Some(arr) = val.as_array() {
                                    if arr.len() == 2 {
                                        where_data.insert(format!("{} between ? and ?", field), val.clone());
                                    }
                                }
                            }
                            "range_str" => {
                                if let Some(arr) = val.as_array() {
                                    if arr.len() == 2 {
                                        where_data.insert(format!("{} between ? and ?", field), val.clone());
                                    }
                                }
                            }
                            "greater" => {
                                if val.is_number() {
                                    where_data.insert(format!("{} > ?", field), val.clone());
                                } else if val.is_string() {
                                    if let Some(v) = val.as_str() {
                                        where_data.insert(format!("{} > ?", field), json!(v.trim()));
                                    }
                                }
                            }
                            "greater_int" => {
                                if val.is_number() {
                                    where_data.insert(format!("{} > ?", field), val.clone());
                                }
                            }
                            "greater_str" => {
                                if val.is_string() {
                                    if let Some(v) = val.as_str() {
                                        where_data.insert(format!("{} > ?", field), json!(v.trim()));
                                    }
                                }
                            }
                            "less" => {
                                if val.is_number() {
                                    where_data.insert(format!("{} < ?", field), val.clone());
                                } else if val.is_string() {
                                    if let Some(v) = val.as_str() {
                                        where_data.insert(format!("{} < ?", field), json!(v.trim()));
                                    }
                                }
                            }
                            "less_int" => {
                                if val.is_number() {
                                    where_data.insert(format!("{} < ?", field), val.clone());
                                }
                            }
                            "less_str" => {
                                if val.is_string() {
                                    if let Some(v) = val.as_str() {
                                        where_data.insert(format!("{} < ?", field), json!(v.trim()));
                                    }
                                }
                            }
                            "greater_equals" => {
                                if val.is_number() {
                                    where_data.insert(format!("{} >= ?", field), val.clone());
                                } else if val.is_string() {
                                    if let Some(v) = val.as_str() {
                                        where_data.insert(format!("{} >= ?", field), json!(v.trim()));
                                    }
                                }
                            }
                            "greater_equals_int" => {
                                if val.is_number() {
                                    where_data.insert(format!("{} >= ?", field), val.clone());
                                }
                            }
                            "greater_equals_str" => {
                                if val.is_string() {
                                    if let Some(v) = val.as_str() {
                                        where_data.insert(format!("{} >= ?", field), json!(v.trim()));
                                    }
                                }
                            }
                            "less_equals" => {
                                if val.is_number() {
                                    where_data.insert(format!("{} <= ?", field), val.clone());
                                } else if val.is_string() {
                                    if let Some(v) = val.as_str() {
                                        where_data.insert(format!("{} <= ?", field), json!(v.trim()));
                                    }
                                }
                            }
                            "less_equals_int" => {
                                if val.is_number() {
                                    where_data.insert(format!("{} <= ?", field), val.clone());
                                }
                            }
                            "less_equals_str" => {
                                if val.is_string() {
                                    if let Some(v) = val.as_str() {
                                        where_data.insert(format!("{} <= ?", field), json!(v.trim()));
                                    }
                                }
                            }
                            "in" => {
                                if let Some(arr) = val.as_array() {
                                    if arr.len() > 0 {
                                        where_data.insert(format!("{} in (?)", field), val.clone());
                                    }
                                }
                            }
                            "in_int" => {
                                if let Some(arr) = val.as_array() {
                                    if arr.len() > 0 {
                                        where_data.insert(format!("{} in (?)", field), val.clone());
                                    }
                                }
                            }
                            "in_str" => {
                                if let Some(arr) = val.as_array() {
                                    if arr.len() > 0 {
                                        where_data.insert(format!("{} in (?)", field), val.clone());
                                    }
                                }
                            }
                            _ => (),
                        }
                    }
                }
            }
        })
    }

    where_data
}

/// 从前台页面传递的数据中提取出数据库排序语句
/// ```
/// vm.searchForm.order$id = "asc";
/// vm.searchForm.order$status = "desc";  
///
/// 生成排序语句 "id asc, status desc"
///
/// ```
///
#[allow(dead_code)]
pub fn get_db_order_str(data: &Value) -> String {
    let mut list: Vec<String> = Vec::new();

    if let Some(obj) = data.as_object() {
        obj.iter().for_each(|item| {
            let key = item.0;
            let val = item.1;

            if let Ok(re) = Regex::new("^order\\$([0-9A-Za-z_]+)$") {
                if let Some(cap) = re.captures(key) {
                    if cap.len() > 1 {
                        let field = cap.get(1).unwrap().as_str();
                        if let Some(v) = val.as_str() {
                            if v.eq("asc") || v.eq("desc") {
                                list.push(format!("{} {} ", field, v));
                            }
                        }
                    }
                }
            }
        });
    }

    list.join(",")
}
